<template>
  <div class="version-viewer-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">版本指标查看</h1>
        <p class="page-subtitle">查看和比较不同版本的技术标准指标</p>
      </div>
      <div class="header-actions">
        <el-select v-model="selectedPaperType" placeholder="选择纸种" style="width: 180px; margin-right: 12px;" @change="onPaperTypeChange">
          <el-option v-for="type in paperTypes" :key="type.value" :label="type.label" :value="type.value" />
        </el-select>
        <el-select v-model="selectedVersions" placeholder="选择版本" multiple style="width: 300px; margin-right: 12px;" @change="onVersionChange">
          <el-option v-for="ver in versionList" :key="ver.id" :label="ver.label" :value="ver.id" />
        </el-select>
        <el-button type="primary" size="large" @click="exportComparison" class="export-btn">
          导出对比
        </el-button>
        <el-button size="large" @click="goBack" class="back-btn">
          返回
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content" v-if="selectedPaperType && selectedVersions.length > 0">
      <!-- 版本对比表格 -->
      <div class="comparison-section">
        <div class="section-header">
          <h3 class="section-title">版本对比</h3>
          <div class="version-tags">
            <el-tag v-for="versionId in selectedVersions" :key="versionId" type="primary" class="version-tag">
              {{ getVersionLabel(versionId) }}
            </el-tag>
          </div>
        </div>
        
        <div class="comparison-table">
          <el-table :data="comparisonData" border stripe class="version-table">
            <el-table-column prop="weight" label="克重 (g/m²)" width="120" fixed="left" />
            <el-table-column prop="grade" label="等级" width="120" fixed="left" />
            <el-table-column prop="indicator" label="指标名称" width="150" fixed="left" />
            <el-table-column prop="unit" label="单位" width="100" fixed="left" />
            
            <!-- 动态版本列 -->
            <el-table-column 
              v-for="versionId in selectedVersions" 
              :key="versionId"
              :label="getVersionLabel(versionId)"
              :prop="`version_${versionId}`"
              min-width="150"
            >
              <template #default="scope">
                <div class="version-cell">
                  <span class="standard-value">{{ scope.row[`version_${versionId}`] || '-' }}</span>
                  <div class="version-info" v-if="scope.row[`version_${versionId}_info`]">
                    <el-tag size="small" :type="getVersionTagType(versionId)">
                      {{ scope.row[`version_${versionId}_info`] }}
                    </el-tag>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 版本详情卡片 -->
      <div class="version-details">
        <div class="section-header">
          <h3 class="section-title">版本详情</h3>
        </div>
        
        <div class="version-cards">
          <div 
            v-for="versionId in selectedVersions" 
            :key="versionId"
            class="version-card"
          >
            <div class="card-header">
              <h4 class="card-title">{{ getVersionLabel(versionId) }}</h4>
              <el-tag :type="getVersionTagType(versionId)" size="small">
                {{ getVersionStatus(versionId) }}
              </el-tag>
            </div>
            
            <div class="card-content">
              <div class="version-info">
                <p><strong>创建时间：</strong>{{ getVersionInfo(versionId)?.createdAt?.slice(0, 19).replace('T', ' ') || '-' }}</p>
                <p><strong>备注：</strong>{{ getVersionInfo(versionId)?.remark || '无' }}</p>
              </div>
              
              <div class="version-stats">
                <div class="stat-item">
                  <span class="stat-number">{{ getVersionStats(versionId).weightCount }}</span>
                  <span class="stat-label">克重类型</span>
                </div>
                <div class="stat-item">
                  <span class="stat-number">{{ getVersionStats(versionId).gradeCount }}</span>
                  <span class="stat-label">等级类型</span>
                </div>
                <div class="stat-item">
                  <span class="stat-number">{{ getVersionStats(versionId).indicatorCount }}</span>
                  <span class="stat-label">技术指标</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 差异分析 -->
      <div class="difference-analysis" v-if="selectedVersions.length > 1">
        <div class="section-header">
          <h3 class="section-title">版本差异分析</h3>
        </div>
        
        <div class="difference-content">
          <el-alert
            v-for="(diff, index) in versionDifferences"
            :key="index"
            :title="diff.title"
            :description="diff.description"
            :type="diff.type"
            show-icon
            :closable="false"
            class="difference-alert"
          />
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-else>
      <div class="empty-icon">📊</div>
      <h3 class="empty-title">请选择纸种和版本</h3>
      <p class="empty-description">选择要查看的纸种类型和版本，系统将显示详细的指标对比信息</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'

const router = useRouter()
const STANDARD_STORAGE_KEY = 'factory_standard_versions'

// 响应式数据
const standardData = ref({})
const selectedPaperType = ref('')
const selectedVersions = ref([])

// 纸种类型列表动态获取，优先从 localStorage 读取 standardPaperTypes
const paperTypes = ref([])

function loadPaperTypes() {
  let types = []
  try {
    const typesRaw = localStorage.getItem('factory_standard_types')
    if (typesRaw) {
      types = JSON.parse(typesRaw)
    }
  } catch {}
  paperTypes.value = types
}

// 计算属性
const versionList = computed(() => {
  if (!selectedPaperType.value || !standardData.value[selectedPaperType.value]) {
    return []
  }
  return standardData.value[selectedPaperType.value].map(v => ({
    id: v.id,
    label: `${v.label}（${v.createdAt.slice(0, 10)}）`
  }))
})

const comparisonData = computed(() => {
  if (!selectedPaperType.value || selectedVersions.value.length === 0) {
    return []
  }

  const data = []
  const paperTypeData = standardData.value[selectedPaperType.value]
  
  selectedVersions.value.forEach(versionId => {
    const version = paperTypeData.find(v => v.id === versionId)
    if (version && version.data) {
      version.data.forEach(weight => {
        weight.grades.forEach(grade => {
          grade.items.forEach(indicator => {
            // 查找是否已存在相同的行
            let existingRow = data.find(row => 
              row.weight === weight.weight && 
              row.grade === grade.grade && 
              row.indicator === indicator.name
            )
            
            if (!existingRow) {
              existingRow = {
                weight: weight.weight,
                grade: grade.grade,
                indicator: indicator.name,
                unit: indicator.unit
              }
              data.push(existingRow)
            }
            
            // 添加版本数据
            existingRow[`version_${versionId}`] = indicator.standard
            existingRow[`version_${versionId}_info`] = version.label
          })
        })
      })
    }
  })
  
  return data
})

const versionDifferences = computed(() => {
  if (selectedVersions.value.length < 2) return []
  
  const differences = []
  const data = comparisonData.value
  
  // 分析差异
  data.forEach(row => {
    const values = selectedVersions.value.map(vId => row[`version_${vId}`]).filter(v => v && v !== '-')
    const uniqueValues = [...new Set(values)]
    
    if (uniqueValues.length > 1) {
      differences.push({
        title: `指标差异：${row.indicator}`,
        description: `${row.weight}g/m² ${row.grade} 的 ${row.indicator} 在不同版本中存在差异`,
        type: 'warning'
      })
    }
  })
  
  return differences
})

// 方法
function onPaperTypeChange() {
  selectedVersions.value = []
}

function onVersionChange() {
  // 版本变化时的处理
}

function getVersionLabel(versionId) {
  const version = standardData.value[selectedPaperType.value]?.find(v => v.id === versionId)
  return version ? version.label : versionId
}

function getVersionInfo(versionId) {
  return standardData.value[selectedPaperType.value]?.find(v => v.id === versionId)
}

function getVersionTagType(versionId) {
  const version = getVersionInfo(versionId)
  if (!version) return 'info'
  
  // 根据版本标签返回不同的类型
  if (version.label.includes('Excel导入')) return 'success'
  if (version.label.includes('初始')) return 'info'
  return 'primary'
}

function getVersionStatus(versionId) {
  const version = getVersionInfo(versionId)
  if (!version) return '未知'
  
  if (version.label.includes('Excel导入')) return '导入版本'
  if (version.label.includes('初始')) return '初始版本'
  return '标准版本'
}

function getVersionStats(versionId) {
  const version = getVersionInfo(versionId)
  if (!version || !version.data) {
    return { weightCount: 0, gradeCount: 0, indicatorCount: 0 }
  }
  
  let weightCount = 0
  let gradeCount = 0
  let indicatorCount = 0
  
  version.data.forEach(weight => {
    weightCount++
    weight.grades.forEach(grade => {
      gradeCount++
      indicatorCount += grade.items.length
    })
  })
  
  return { weightCount, gradeCount, indicatorCount }
}

function exportComparison() {
  try {
    const exportData = []
    
    // 表头
    const headers = ['克重 (g/m²)', '等级', '指标名称', '单位']
    selectedVersions.value.forEach(versionId => {
      headers.push(getVersionLabel(versionId))
    })
    exportData.push(headers)
    
    // 数据行
    comparisonData.value.forEach(row => {
      const dataRow = [row.weight, row.grade, row.indicator, row.unit]
      selectedVersions.value.forEach(versionId => {
        dataRow.push(row[`version_${versionId}`] || '-')
      })
      exportData.push(dataRow)
    })
    
    // 创建工作簿
    const worksheet = XLSX.utils.aoa_to_sheet(exportData)
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '版本对比')
    
    // 设置列宽
    const colWidths = [
      { wch: 12 }, // 克重
      { wch: 10 }, // 等级
      { wch: 15 }, // 指标名称
      { wch: 8 },  // 单位
    ]
    selectedVersions.value.forEach(() => {
      colWidths.push({ wch: 15 }) // 每个版本列
    })
    worksheet['!cols'] = colWidths
    
    // 下载文件
    const fileName = `${selectedPaperType.value}_版本对比_${new Date().toISOString().slice(0, 10)}.xlsx`
    XLSX.writeFile(workbook, fileName)
    ElMessage.success('版本对比文件已导出')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

function goBack() {
  router.back()
}

// 生命周期
onMounted(() => {
  const raw = localStorage.getItem(STANDARD_STORAGE_KEY)
  if (raw) {
    try {
      standardData.value = JSON.parse(raw)
    } catch (error) {
      console.error('加载数据失败:', error)
    }
  }
  loadPaperTypes()
})
</script>

<style scoped>
.version-viewer-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

/* 页面头部 */
.page-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 24px 32px;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.header-content {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0 0 5px 0;
}

.page-subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.export-btn {
  background: linear-gradient(135deg, #20c997, #17a2b8);
  border: none;
  border-radius: 8px;
  font-weight: 600;
  box-shadow: 0 4px 16px rgba(32, 201, 151, 0.3);
  transition: all 0.3s ease;
}

.export-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(32, 201, 151, 0.4);
}

.back-btn {
  border-radius: 8px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.back-btn:hover {
  transform: translateY(-2px);
}

/* 主要内容区域 */
.main-content {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 对比表格区域 */
.comparison-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.version-tags {
  display: flex;
  gap: 8px;
}

.version-tag {
  font-weight: 500;
}

.comparison-table {
  overflow-x: auto;
}

.version-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.version-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.standard-value {
  font-weight: 500;
  color: #1a1a1a;
}

.version-info {
  display: flex;
  justify-content: center;
}

/* 版本详情卡片 */
.version-details {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.version-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.version-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e9ecef;
  transition: all 0.3s ease;
}

.version-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.card-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.version-info p {
  margin: 4px 0;
  font-size: 14px;
  color: #666;
}

.version-stats {
  display: flex;
  justify-content: space-around;
  gap: 16px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #667eea;
  line-height: 1;
}

.stat-label {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

/* 差异分析 */
.difference-analysis {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.difference-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.difference-alert {
  border-radius: 8px;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  text-align: center;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 24px;
  opacity: 0.6;
}

.empty-title {
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 12px 0;
}

.empty-description {
  font-size: 16px;
  color: #666;
  margin: 0;
  max-width: 400px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .version-viewer-container {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .header-actions {
    width: 100%;
    justify-content: center;
  }
  
  .version-cards {
    grid-template-columns: 1fr;
  }
  
  .version-stats {
    flex-direction: column;
    gap: 12px;
  }
  
  .comparison-table {
    font-size: 12px;
  }
}
</style> 